package com.goldsprite.contourextraction.core;

//import javax.imageio.ImageIO;
//import java.awt.image.BufferedImage;
//import java.awt.image.WritableRaster;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class ContourTracerApp {

	// 测试方法
	public static void main(String[] args) {

		// 测试数据
		int[][] testGrid = ImageUtils.createTestImage();

		testContourTrace(testGrid, false);

//		// 实际图片演示
//		String path1 = "libgdx.png";
//		String path2 = "grass.png";
//		String path = path2;
//		int[][] testImageGrid = ImageUtils.reverseY(loadAndProcessRealImage(path));
//		if (testImageGrid != null) {
//			testContourTrace(testImageGrid, false);
//		}
	}

	public static List<Contour> testContourTrace(int[][] testGrid, boolean onlyVertex) {
		return testContourTrace(testGrid, onlyVertex, true);
	}
	public static List<Contour> testContourTrace(int[][] testGrid, boolean onlyVertex, boolean printVisualization) {
		return testContourTrace(testGrid, onlyVertex, false, printVisualization);
	}
	public static List<Contour> testContourTrace(int[][] testGrid, boolean onlyVertex, boolean onlyOutLine, boolean printVisualization) {
		ContourTracer tracer = new ContourTracer();
		List<Contour> contours = tracer.traceContours(testGrid, onlyVertex, onlyOutLine);

		System.out.println("找到 " + contours.size() + " 个轮廓");
		for (int i = 0; i < contours.size(); i++) {
			Contour contour = contours.get(i);
			System.out.println("轮廓 " + i + " 起始点: (" + contour.startX + ", " + contour.startY + ")");
			System.out.println("链码(数量" + contour.chainCodes.size() + "): " + contour.chainCodes);
			if(printVisualization) {
				System.out.println("顶点可视化: ");
				new ContourVisualizer().visualizeContours(testGrid, contours.get(i));
			}
		}

		return contours;
	}

//	/**
//	 * 从resources加载实际图片并处理
//	 */
//	private static int[][] loadAndProcessRealImage(String path) {
//		try {
//			System.out.println("\n=== 处理实际图片 grass.png ===");
//			InputStream inputStream = ContourTracerApp.class.getClassLoader().getResourceAsStream(path);
//			BufferedImage image = ImageIO.read(inputStream);
//			System.out.println("图片尺寸: " + image.getWidth() + " x " + image.getHeight());
//			// 转换为二值数组
//			return convertToBinaryArray(image);
//		} catch (IOException e) {
//			throw new RuntimeException(e);
//		}
//	}
//
//	/**
//	 * 将BufferedImage转换为二值数组
//	 */
//	private static int[][] convertToBinaryArray(BufferedImage image) {
//		int width = image.getWidth();
//		int height = image.getHeight();
//		int[][] binaryArray = new int[height][width];
//
//		// 简单的二值化处理
//		WritableRaster raster = image.getAlphaRaster();
//		int[] aArr = new int[1];
//		for (int y = 0; y < height; y++) {
//			for (int x = 0; x < width; x++) {
//				int a = image.getRGB(x, y);
//				if (raster != null) a = raster.getPixel(x, y, aArr)[0];
//				binaryArray[y][x] = a > 0 ? ImageConstants.FOREGROUND : ImageConstants.BACKGROUND;
//			}
//		}
//
//		return binaryArray;
//	}
}
